package controller

import (
	"cmdb/base/Controller/Base"
	"cmdb/errors"
	"cmdb/forms"
	"cmdb/models"
	"github.com/astaxie/beego"
	"net/http"
)

type AuthController struct {
	Base.MainController
}

//认证登录
func (c *AuthController) Login() {
	form := &forms.LoginForm{}
	e := errors.New()
	//如果是get请求，直接请求页面
	if c.Ctx.Input.IsGet() {
		c.TplName = "home/Index.html"
	}
	//如果是post请求，验证数据
	if c.Ctx.Input.IsPost() {
		//获取用户提交数据
		err := c.ParseForm(form) //解析表单
		if err == nil {
			user := models.GetUser(form.UserName)
			if user == nil {
				//用户不存在,将错误添加到map中
				e.Add("default", "用户不存在")
			} else if user.ValidPassword(form.PassWord) {
				sessionKey := beego.AppConfig.DefaultString("auth::SessionKey", "user")
				//用户密码正确
				c.SetSession(sessionKey, user.ID) //设置Session
				queryAction := beego.AppConfig.DefaultString("auth::IndexAction", "HomeController.Index")
				Path := beego.URLFor(queryAction)
				c.Redirect(Path, http.StatusFound) //跳转主页，返回状态码302
			} else {
				e.Add("default", "密码错误")
			}
		} else {
			e.Add("default", "用户或者密码错误")
		}
		//验证成功
		//验证失败
	}
	c.Data["form"] = form
	c.Data["errors"] = e //将值传送给模板
	c.TplName = "auth/login.html"
	//如果是post请求，判断数据库的增删查改
	//请求页面
}
func (c *AuthController) LoginOut() {
	c.DestroySession() //清理Cookie
	loginoutAction := beego.AppConfig.DefaultString("auth::LoginOutAction", "AuthController.Login")
	c.Redirect(beego.URLFor(loginoutAction), http.StatusFound)
}
